<?php

session_start();
require 'class.DB.php';

$log_usr = 1;
$pas_usr = 1;
$log_usr = $_POST['log_usr']; // получаем логин
$pas_usr = $_POST['pas_usr']; // получаем пароль
$map_id = $pas_usr;
$end_game = 0;

if ($pas_usr != "")
{

    $send = ' ';


    if ($log_usr == 'l')
    {
        $result = mysql_query('SELECT prof,log FROM chat ', $db);

        $send = '';
        while ($myrow = mysql_fetch_array($result))
        {
            $send .= '[' . $myrow["prof"] . '] : ' . $myrow["log"] . " \n";
        }
    }
    
    if ($log_usr == 'chat')
    {
        $send = 'chat ' . $map_id;
        mysql_query("UPDATE map SET player=1,init=0 where  id='" . $map_id . "'", $db);
        
    }

    ///ref _table*********************************************************************************
    if ($log_usr == 'refresh_table')
    {
        mysql_query("UPDATE map SET player=1,init=0 where  id='" . $map_id . "'", $db);
        //  mysql_query("UPDATE map SET init=0 where  id='".$map_id."'", $db);
        //
        // mysql_query("UPDATE planet SET power=30  where  map='".$map_id."'", $db);
        // mysql_query("UPDATE planet SET player=-1  where  map='".$map_id."'", $db);
        //  mysql_query("UPDATE planet SET r=power  where  map='".$map_id."'", $db);
        //  mysql_query("UPDATE planet SET ships=1000  where  map='".$map_id."'", $db);
        mysql_query("UPDATE planet SET power=30,player=-1,r=power,ships=1000   where  map='" .
            $map_id . "'", $db);
        mysql_query("UPDATE planet SET player=1 where  map='" . $map_id . "' and num=1 ",
            $db);

        $send = 'refresh_table map ' . $map_id;

    }

    ///player*********************************************************************************
    if ($log_usr == 'player')
    {
        //player +1
        //  if palyer<max[layer]]
        
        $result = mysql_query("SELECT init FROM map WHERE id='".$map_id."'");
        $myrow = mysql_fetch_array($result);
        $g_init = $myrow['init'];
        
        if ($g_init==0)
          
  
     
        mysql_query("UPDATE  map SET player=player+1 WHERE id='" . $map_id . "'", $db);

        $result = mysql_query("SELECT num from planet where player=-1 and map='" . $map_id ."'");
        $myrow = mysql_fetch_array($result);
        $t_player = $myrow['num'];


        // if (isset ($_SESSION['user']))

        if (isset($_SESSION['id']))
        {
            $id_user = $_SESSION['id'];
        } else
        {
            mysql_query("INSERT INTO user( pass , mail ,rank )VALUES
                    ( 'guestnn','guest@mail.ru',2000 )");
            $ai = mysql_insert_id();
            $ai_str = 'Guest' . $ai;
            mysql_query("Update user set login='" . $ai_str . "' where id='" . $ai . "' ");
            $_SESSION['id'] = $ai;
            $_SESSION['user'] = $ai_str;
            $id_user = $ai;
        }


        mysql_query("Update user set win=0,map='" . $map_id . "',num='" . $t_player .
            "'  where id='" . $id_user . "' ");

        //  mysql_query("INSERT INTO  (map_id,user_id,player_num,win) VALUE
        // ('".$map_id."' , '".$id_user."', '".$t_player."',0)",$db);

        mysql_query("UPDATE planet SET player='".$t_player."',POWER=30,r=30,ships=1000 WHERE
        map='" . $map_id . "' AND num='" . $t_player . "' ");


        $send = 'player '.$t_player.' ';
        $result = mysql_query("SELECT id,player,num  FROM planet WHERE player>-1 and map='" .
            $map_id . "'", $db);
        while ($myrow = mysql_fetch_array($result))
        {
            $res_user = mysql_query("SELECT login,rank,win  FROM user 
            WHERE num='" . $myrow['num'] . "'  and map='" . $map_id . "'", $db);
            $myrow_user = mysql_fetch_array($res_user);

            $send .= $myrow_user['login'] . ' rank ' . $myrow_user['rank'] . ' win ' . $myrow_user['win'] .
                ' ' . $myrow['player'] . ' ' . $myrow['num'] . ' ' . " \n ";
        }
    }


    ///map*********************************************************************************
    if ($log_usr == 'map')
    {
        $send = 'map ';
        $result = mysql_query('SELECT count(id) FROM map  ', $db);
        $myrow = mysql_fetch_array($result);
        $send .= $myrow['count(id)'] . ' ';
        $result = mysql_query('SELECT id,name,max_players,player  FROM map ORDER BY player DESC ',
            $db);
        // $myrow = mysql_fetch_array($result);
        while ($myrow = mysql_fetch_array($result))
        {
            $send .= $myrow['id'] . ' ' . $myrow['name'] . ' ' . $myrow['max_players'] . ' ' .
                $myrow['player'] . ' ';
        }
    }


    ///ships*********************************************************************************
    if ($log_usr == 'ships')
    {

        $t_power = $_POST['tarshippower'];
        if ($t_power > 1)
            $t_power = 1;
        if ($t_power < 0)
            $t_power = 0;
        $tarshipdest = $_POST['tarshipdest'];
        $tarshipfrom = $_POST['tarshipfrom'];

        $result = mysql_query("SELECT ships  FROM planet 
        WHERE id='" . $tarshipfrom . "'", $db);
        $myrow = mysql_fetch_array($result);
        {
            $tarshippower = round($t_power * $myrow['ships']);
        }


        mysql_query("INSERT INTO ships  (from_id,dest_id,count_ships) 
        VALUE ('" . $tarshipfrom . "','" . $tarshipdest . "','" . $tarshippower .
            "')", $db);

        //  $res_maxid = mysql_fetch_array(mysql_query("SELECT  ships_id FROM ships WHERE
        //  ships_id=(SELECT MAX(ships_id) FROM ships) "));
        //   $maxid = $res_maxid["ships_id"];
        $maxid = mysql_insert_id();

        mysql_query("UPDATE  ships 
        SET X =  ( SELECT X FROM planet WHERE id ='" . $tarshipfrom . "' ) 
        ,Y =  ( SELECT Y FROM planet WHERE id ='" . $tarshipfrom . "' )
        ,XK =  ( SELECT X FROM planet WHERE id ='" . $tarshipdest . "' )
        ,YK =  ( SELECT Y FROM planet WHERE id ='" . $tarshipdest . "' ) 
        ,User_id =  ( SELECT player FROM planet WHERE id ='" . $tarshipfrom .
            "' )
        ,map =  ( SELECT map FROM planet WHERE id ='" . $tarshipfrom . "' )
        WHERE ships_id='" . $maxid . "'", $db);

        mysql_query("UPDATE  planet SET ships = ships- '" . $tarshippower . "'
        WHERE id='" . $tarshipfrom . "'", $db);


        $result = mysql_query("SELECT id,player,ships   FROM planet WHERE map='" . $map_id .
            "'", $db);
        $send = $end_game . " ";
        while ($myrow = mysql_fetch_array($result))
        {
            $send .= $myrow['id'] . ' ' . $myrow['player'] . ' ' . $myrow['ships'] . ' ';
        }
        $res_maxid = mysql_fetch_array(mysql_query("SELECT COUNT(ships_id) FROM ships WHERE map='" .
            $map_id . "'"));
        $send .= $res_maxid["COUNT(ships_id)"] . ' ';
        $result = mysql_query("SELECT dest_id,x,y,xk,yk,rot,user_id,count_ships,ships_id   
           FROM ships WHERE map='" . $map_id . "'", $db);

        while ($myrow = mysql_fetch_array($result))
        {
            $send .= $myrow['ships_id'] . ' ' . $myrow['dest_id'] . ' ' . $myrow['x'] . ' ' .
                $myrow['y'] . ' ' . $myrow['xk'] . ' ' . $myrow['yk'] . ' ' . $myrow['user_id'] .
                ' ' . $myrow['count_ships'] . ' ';
        }
    }


    if ($log_usr == 'planet')
    {

        //**********************************end game
        $end_game = mysql_query("SELECT  DISTINCT player  FROM planet WHERE map='" . $map_id .
            "' &&  player!=-1 ", $db);
        if ((mysql_num_rows($end_game) == 1))
        {
            $ships_end = mysql_query("SELECT user_id FROM ships  WHERE map='" . $map_id .
                "'", $db);
            if (mysql_num_rows($ships_end) > 0)
            {
                $planet_res = mysql_query("SELECT player  FROM planet WHERE map='" . $map_id .
                    "' &&  player!=-1 ", $db);
                $planet_row = mysql_fetch_array($planet_res);
                $planet_end = $planet_row['player'];

                $end_game = 1;
                while ($myrow = mysql_fetch_array($ships_end))
                {
                    if ($myrow['user_id'] != $planet_end)
                        $end_game = 0;
                }
            } else
                $end_game = 1;
        } else
            $end_game = 0;

        if ($end_game == 1)
        {
            mysql_query("UPDATE map SET player=0 where  id='" . $map_id . "'", $db);
            mysql_query("UPDATE map SET init=0 where  id='" . $map_id . "'", $db);
            mysql_query("UPDATE planet SET power=30,player=-1,r=power,ships=1000   where  map='" .
                $map_id . "'", $db);
           mysql_query("DELETE ships FROM ships WHERE map='".$map_id."' "); //udoleneie carable zakrivsheisia karti
        }
        $send = $end_game . " ";


        $result = mysql_query("SELECT id,player,ships   FROM planet WHERE map='" . $map_id .
            "'", $db);
        while ($myrow = mysql_fetch_array($result))
        {
            $send .= $myrow['id'] . ' ' . $myrow['player'] . ' ' . $myrow['ships'] . ' ';
        }

        function getmicrotime()
        {
            list($usec, $sec) = explode(" ", microtime());
            return ((float)$usec + (float)$sec);
        }
        $time = time();
        $mtime = getmicrotime();

        $result = mysql_query("SELECT time_msec   FROM map WHERE id='" . $map_id . "'",
            $db);
        $myrow = mysql_fetch_array($result);

        $mtime2 = $myrow['time_msec'];

        $mtime_res = $mtime - $mtime2;
        if ($mtime_res > 0.3)
        {
            /// UVELICHENIE SHiPS NA PLANETAH
            mysql_query("UPDATE planet SET ships=ships+POWER WHERE player>0 and map='" . $map_id .
                "'", $db);

            mysql_query("UPDATE  map SET time_msec='" . $mtime . "' WHERE id='" . $map_id .
                "' ", $db);

            mysql_query("    UPDATE ships SET  X=X+ 7* (xk-X)/SQRT( (xk-X)*(xk-X) + (yk-Y)*(yk-Y) )
     ,Y=Y+ 7* (yk-Y)/SQRT( (xk-X)*(xk-X) + (yk-Y)*(yk-Y) )
    ,rot=ATAN2((yk-Y),(xk-X))*180/3.14; ", $db);
        }

        /// **** destanation tru
        $result = mysql_query("SELECT x,y,xk,yk,dest_id,count_ships,user_id,ships_id   FROM ships 
        WHERE map='" . $map_id . "'", $db);

        while ($myrow = mysql_fetch_array($result))
        {
            $result_planet = mysql_query("SELECT r  FROM planet WHERE id='" . $myrow['dest_id'] .
                "'", $db);
            $myrow_planet = mysql_fetch_array($result_planet);
            $radius = $myrow_planet['r']; ///*****Radius

            if (sqrt(($myrow['x'] - $myrow['xk']) * ($myrow['x'] - $myrow['xk']) + ($myrow['y'] -
                $myrow['yk']) * ($myrow['y'] - $myrow['yk'])) < $radius + 28)
            {
                $zap_res = mysql_fetch_array(mysql_query("SELECT player FROM planet
                     WHERE id ='" . $myrow['dest_id'] . "'", $db));
                $player = $zap_res['player'];
                if ($myrow['user_id'] == $player)
                {
                    mysql_query("UPDATE  planet SET ships=ships +
                          '" . $myrow['count_ships'] . "' WHERE id='" . $myrow['dest_id'] .
                        "'", $db);
                }
                if ($myrow['user_id'] != $player)
                {
                    mysql_query("UPDATE  planet SET ships=ships -
                          '" . $myrow['count_ships'] . "' WHERE id='" . $myrow['dest_id'] .
                        "'", $db);

                    $zap_ships = mysql_fetch_array(mysql_query("SELECT ships FROM planet
                       WHERE id ='" . $myrow['dest_id'] . "'", $db));
                    $zap = $zap_ships['ships'];
                    if ($zap < 0)
                    {
                        mysql_query("UPDATE  planet SET ships=-ships ,player='" . $myrow['user_id'] . "'
                           WHERE id='" . $myrow['dest_id'] . "'", $db);
                    }
                }
                mysql_query("DELETE ships FROM ships WHERE ships_id='" . $myrow['ships_id'] .
                    "'", $db);
            } ///  ****************************************************** destanation tru <5
        } ///  ****************************************************** massiv perebor tru


        //   $send .= $mtime_res.' '
        $res_maxid = mysql_fetch_array(mysql_query("SELECT COUNT(ships_id) FROM ships WHERE map='" .
            $map_id . "'"));
        $send .= $res_maxid["COUNT(ships_id)"] . ' ';
        $result = mysql_query("SELECT dest_id,x,y,xk,yk,rot,user_id,count_ships,ships_id   
           FROM ships WHERE map='" . $map_id . "'", $db);

        while ($myrow = mysql_fetch_array($result))
        {
            $send .= $myrow['ships_id'] . ' ' . $myrow['dest_id'] . ' ' . $myrow['x'] . ' ' .
                $myrow['y'] . ' ' . $myrow['xk'] . ' ' . $myrow['yk'] . ' ' . $myrow['user_id'] .
                ' ' . $myrow['count_ships'] . ' ';
        }

        $send .= 'endplanet2';
    }

    if ($log_usr == 'init')
    {
        //  Sozdanie planet
        // $result = mysql_query("SELECT init FROM map WHERE id='".$map_id."'",$db);
        //  $myrow = mysql_fetch_array($result);
        //  if ($myrow ['init']==0) {


        mysql_query("UPDATE  map SET init=init+1  WHERE id='" . $map_id . "'", $db);
        //  if init=1
        $result = mysql_query("SELECT init FROM map WHERE id='" . $map_id . "'", $db);
        $myrow = mysql_fetch_array($result);
        $init_game = $myrow['init'];

        //  $ran= rand(5, 15);
        if ($init_game == 1)
        {
            $result = mysql_query("SELECT id,player  FROM planet WHERE map='" . $map_id .
                "' AND player=-1", $db);
            while ($myrow = mysql_fetch_array($result))
            {
                $ran = rand(5, 29);
                $ran_ship = $ran * 10 + rand(5, 30) * 10;
                mysql_query("UPDATE  planet SET POWER='" . $ran . "' , ships='" . $ran_ship .
                    "' ,r='" . $ran . "'
           WHERE player=-1  AND map='" . $map_id . "' AND id='" . $myrow['id'] .
                    "'", $db);
            }
        }


        $send = '';
        // create nw planet
        $result = mysql_query("SELECT id,name,max_players,max_planet,player   FROM map WHERE id='" .
            $map_id . "'", $db);
        $myrow = mysql_fetch_array($result);
        $send .= $myrow['id'] . ' ' . $myrow['name'] . ' ' . $myrow['max_players'] . ' ' .
            $myrow['max_planet'] . ' ' . $myrow['player'] . ' ';

        $result = mysql_query("SELECT id,power,r,player,x,y,ships   FROM planet WHERE map='" .
            $map_id . "' ", $db);
        while ($myrow = mysql_fetch_array($result))
        {
            $send .= $myrow["id"] . ' ' . $myrow["power"] . ' ' . $myrow["r"] . ' ' . $myrow["player"] .
                ' ' . $myrow["x"] . ' ' . $myrow["y"] . ' ' . $myrow["ships"] . ' ';
        }

        function getmicrotime()
        {
            list($usec, $sec) = explode(" ", microtime());
            return ((float)$usec + (float)$sec);
        }

        $time = time();
        $mtime = getmicrotime();
        $send .= $time . ' end1';

        mysql_query("UPDATE  map SET time_start='" . $time . "', time_msec_start='" . $mtime .
            "'
         WHERE id='" . $map_id . "' ", $db);
    }

    if (($log_usr == "r") || ($log_usr == "a"))
    {
        $result = mysql_query('SELECT num FROM chat WHERE id=1 ', $db);
        $myrow = mysql_fetch_array($result);
        $times = $myrow['num'];
        $times = $times + 1;

        mysql_query("UPDATE chat SET num='" . strtolower($times) . "' WHERE id= 1 ", $db);
        //$res=mysql_query("UPDATE chat SET log='".strtolower($pas_usr)."' WHERE id= 2 ", $db );
        mysql_query("INSERT INTO  chat  (log,num) VALUES('" . strtolower($pas_usr) .
            "','" . strtolower($times) . "')", $db);
        //$res=mysql_query("INSERT INTO  chat  (log,num) VALUES('2s',22)", $db );
        $send = "change " . $times;
    }

    $send = iconv('cp1251', 'utf-8', $send);
    echo $send;
}

?>